package com.hy.service.impl;

import com.auth0.jwt.exceptions.JWTCreationException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.dao.Ums_memberMapper;
import com.hy.entitys.hy_front_userdb.Ums_member;
import com.hy.entitys.hy_front_userdb.Us_tp;
import com.hy.service.FaceService;
import com.hy.service.IUms_memberService;
import com.hy.service.IUs_tpService;
import com.hy.service.NoteService;
import com.hy.utils.*;
import com.hy.utils.download.HeardDownload;
import com.hy.utils.face.Setingmodel;
import com.hy.utils.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.Map;

/**
 * 会员 服务实现类
 * @author HUAYI
 * @since 2020-12-14
 */
@Service
public class Ums_memberServiceImpl extends ServiceImpl<Ums_memberMapper, Ums_member> implements IUms_memberService {

    @Autowired
    private FaceService fs;

    //获取redis
    @Autowired
    private RedisUtil red;

    //验证码 - 服务
    @Autowired
    private NoteService nts;

    //登录类型 服务
    @Autowired
    private IUs_tpService iuts;

    //图片位置
    @Value("${download.path}")
    private String pathImg;

    //默认图片
    @Value("${download.img}")
    private String img;

    //会员 数据层
    @Resource
    private Ums_memberMapper ums_memberMapper;

    /**
     * 手机验证码注册
     * @param phone
     * @param province
     * @param city
     * @param password
     * @return
     */
    @Override
    public HY_Result phoneCodeReg(String phone, String code, String province, String city, String password) throws SQLException {
        HY_Result rs = nts.checkVerification(phone, code);
        if (rs.isSuccess()){
            //判断手机号是否存在
            if (verifyPhone(phone)) {
                //已存在
                return HY_Result.USER_ALREADY();
            } else {
                //手机注册
                Ums_member ums_member = new Ums_member();
                ums_member.setLevelId(1);
                //如果是手机号直接注册的username就给我们自己默认的
                ums_member.setUsername("@" + phone);
                ums_member.setMobile(phone);
                String zuhe = "{\"province\":" + province + ",\"city\":" + city + "}";
                ums_member.setCity(zuhe);
                ums_member.setHeader("hy_userdb/images/moren.png");
                ums_member.setCreateTime(new Date());
                HY_Result hs = register(ums_member);
                //会员新增成功
                if (hs.isSuccess()){
                    Us_tp ut = new Us_tp();
                    ut.setUsTpUid(ums_member.getId());
                    ut.setUsTpTid(1);
                    ut.setUsTpSign(Md5Utils.getMd5Code(password));
                    if (iuts.save(ut)) {
                        //绑定成功
                        return hs;
                    } else {
                        throw new SQLException("增加验证类型异常!");
                    }
                }
                return hs;
            }
        }
        return rs;
    }

    /**
     * 第三方注册
     * @param qlmap
     * @return
     */
    //开启事务
    @Transactional
    @Override
    public HY_Result third_Reg(Map<String, Object> qlmap) throws SQLException, IOException {
        if (!ObjectUtils.isEmpty(qlmap)) {
            String phone = qlmap.get("phone").toString();
            String code = qlmap.get("code").toString();
            //手机号验证码(匹配)
            HY_Result rscv = nts.checkVerification(phone, code);
            if (rscv.isSuccess()) {
                String _qiq = qlmap.get("_qiq").toString();
                if (red.exists(_qiq)) {
                    //获取缓存中(第三方用户数据)
                    rscv = (HY_Result) red.get(_qiq);
                    ThirdParty tp = (ThirdParty) rscv.getData();
                    //头像
                    String headname = null;
                    //会员
                    Ums_member um = new Ums_member();
                    //新增 第三方登录
                    Us_tp ut = new Us_tp();
                    switch (tp.getSource()) {
                        //QQ登录
                        case "QQ":
                            //会员数据传递
                            headname = tp.getAvatar();
                            um.setHeader(tp.getAvatar());
                            ut.setUsTpTid(2);
                            ut.setUsTpSign(Md5Utils.getMd5Code(tp.getUuid()));
                            break;
                        //支付宝登录
                        case "ALIPAY":
                            //会员数据传递
                            um.setHeader(tp.getAvatar());
                            headname = tp.getAvatar();
                            ut.setUsTpTid(4);
                            ut.setUsTpSign(Md5Utils.getMd5Code(tp.getUid()));
                            break;
                        //微博登录
                        case "WEIBO":
                            //会员数据传递
                            um.setHeader(tp.getAvatar_large());
                            headname = tp.getAvatar_large();
                            ut.setUsTpTid(3);
                            ut.setUsTpSign(Md5Utils.getMd5Code(tp.getUid()));
                            break;
                        //人脸登录
                        case "FACE":
                            //会员数据传递
                            ut.setUsTpTid(5);
                            //生成随机 人脸用户id
                            ut.setUsTpSign(Md5Utils.getMd5Code(SaltUtils.getSalt(16)));
                            break;
                        default:
                            System.out.println("请求错误!");
                            break;
                    }
                    //根据手机号判断会员(是否存在) 如果已存在获取id(检查是否已绑定当前第三方登录)
                    Ums_member u = findPhone(phone);
                    ut.setUsTpUid(!ObjectUtils.isEmpty(u) ? u.getId() : null);
                    //路径配置
                    String path = pathImg + SaltUtils.getSalt(6) + ".jpg";
                    HY_Result rs = new HY_Result();
                    if (ObjectUtils.isEmpty(iuts.sign_Exist(ut))) {
                        if (ObjectUtils.isEmpty(u)){
                            um.setLevelId(1);
                            um.setUsername(tp.getUsername() == null ? "@" + phone : tp.getUsername());
                            um.setMobile(phone);
                            //封装位置 信息
                            String location = "{\"province\":" + qlmap.get("province").toString() + ",\"city\":" + qlmap.get("city").toString() + "}";
                            um.setCity(location);
                            um.setGender(tp.getGender() == null ? null : Byte.valueOf(tp.getGender()));
                            um.setCreateTime(new Date());
                            //赋值给会员对象
                            um.setHeader(!ObjectUtils.isEmpty(headname) ? path : img);
                            //注册 会员
                            rs = this.register(um);
                            if (rs.isSuccess()) {
                                u = um;
                            } else {
                                //注册失败
                                throw new SQLException("会员注册失败!");
                            }
                        }
                        //人脸注册
                        if (ut.getUsTpTid() == 5) {
                            Setingmodel sg = new Setingmodel();
                            sg.setImgpath(tp.getAvatar());
                            sg.setGroupID("YJ");
                            //用户密码
                            sg.setUserID(ut.getUsTpSign());
                            if(!fs.faceRegistration(sg).isSuccess()){
                                throw new RuntimeException("人脸注册失败!");
                            }
                        }
                        //增加 类型验证
                        //传入id
                        ut.setUsTpUid(u.getId());
                        if (iuts.save(ut)) {
                            if (!ObjectUtils.isEmpty(headname)){
                                //图片缓存到本地
                                HeardDownload.HdDownload(headname, path);
                            }
                            //绑定成功
                            return new HY_Result(ResultCode.SUCCESS, ObjectUtils.isEmpty(rs.getData()) ? iuts.Um_JWT_Token(u) : rs.getData(), "https://www.baidu.com/");
                        } else {
                            throw new SQLException("增加验证类型异常!");
                        }
                    }
                    //操作失败
                    return HY_Result.FAILURE();
                }
            }
            return rscv;
        }
        //参数异常
        return HY_Result.INVALID_PARAMETERS();
    }

    /**
     * 会员名验证会员是否注册
     * @param username
     * @return
     */
    @Override
    public HY_Result userNameVerify(String username){
        return ObjectUtils.isEmpty(this.getOne(new QueryWrapper<Ums_member>().eq("username",username))) ? HY_Result.FAILURE() : HY_Result.SUCCESS();
    }

    /**
     * 手机号-密码-登录
     * @param phone
     * @param password
     * @return
     */
    @Override
    public HY_Result phonePwdLogin(String phone, String password) {
        //根据手机号获取会员
        Ums_member um = findPhone(phone);
        if (!ObjectUtils.isEmpty(um)){
            Us_tp ut = new Us_tp();
            //会员id
            ut.setUsTpUid(um.getId());
            //登录类型
            ut.setUsTpTid(1);
            ut.setUsTpSign(Md5Utils.getMd5Code(password));
            //根据会员id 签名(密码) 匹配--->登录
            return iuts.Ut_JWT_Token(ut);
        }
        //用户不存在
        return HY_Result.USER_THERE();
    }

    /**
     * 根据手机号获取会员
     * @param phone
     * @return
     */
    @Override
    public Ums_member findPhone(String phone) {
        return this.getOne(new QueryWrapper<Ums_member>().eq("mobile", phone));
    }

    /**
     * 根据id获取会员
     * @param uid
     * @return
     */
    @Override
    public Ums_member findUid(Integer uid) {
        return this.getById(uid);
    }

    /**
     * 会员注册
     * @param ums_member
     * @return
     */
    //开启事务
    @Transactional
    @Override
    public HY_Result register(Ums_member ums_member) throws SQLException {
        if (ums_memberMapper.third_reg(ums_member) > 0){
            String token;
            try {
                //第一个参数 Map<String,String>(只能为Stringg类型),第二个参数时间(单位分钟)
                token = JWTUtils.getToken(MapReflect.t_mapS(findUid(ums_member.getId())),30);
            } catch (Exception e) {
                throw new JWTCreationException("JWT加密异常!", new RuntimeException());
            }
            //注册成功
            return new HY_Result(ResultCode.SUCCESS,token,"https://www.baidu.com/");
        }
        throw new SQLException("会员手机号注册失败!");
    }

    /**
     * 验证手机号是否存在
     * @param phone
     * @return
     */
    @Override
    public boolean verifyPhone(String phone) {
        return ums_memberMapper.verifyPhone(phone) > 0;
    }
}
